package com.lml.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @date 2020/3/21 11:28
 * Description:
 */
public class DemoTest05 {

    public static void main(String[] args) {
//        String testStr = "eabcb";
//        String testStr = "ababc";
//        String testStr = "abacab";
        String testStr = "ac";
//        String s = longestPalindrome(testStr);
//        System.out.println(s);
        System.out.println("-----------------");
        String s2 = longestPalindrome2(testStr);
        System.out.println(s2);
    }


    public static String longestPalindrome(String s) {
        if (s.length() == 1 || "".equals(s.trim())) return s;
        char c = ' ';
        int index = -1;
        //正序字符串
        String s1 = "";
        //逆序字符串
        String s2 = "";
        List<String> list = new ArrayList<>();
        for (int i = 0; i < s.length(); i++) {
            c = s.charAt(i);
            index = s.lastIndexOf(c);
            while (index > s1.indexOf(c)) {
                //将字符串的正序和倒序相比,true即为回文字符串
                s1 = s.substring(i, index + 1);
                s2 = new StringBuffer(s1).reverse().toString();
                if (s1.equals(s2)) {
                    System.out.println("加入字符串:" + s1);
                    list.add(s1);
                }
                index = s.substring(i, index).lastIndexOf(c);
            }
        }
        list.sort((x, y) -> y.length() - x.length());
        return list.get(0);
    }

    /**
     * 5. 最长回文子串
     * https://leetcode-cn.com/problems/longest-palindromic-substring/
     * 给定一个字符串 s，找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
     *
     * @param s 字符串参数
     * @return 最长回文子串
     */
    public static String longestPalindrome2(String s) {
        if (s.length() == 1 || "".equals(s.trim())) return s;
        char c = ' ';
        int index = -1;
        //正序字符串
        String s1 = "";
        //逆序字符串
        String s2 = "";
        List<String> list = new ArrayList<>();
        String str = s;
        for (int i = 0; i < s.length(); i++) {
            str = s.substring(i);
            c = str.charAt(0);
            index = str.lastIndexOf(c);
            while (index >= 0) {
                s1 = str.substring(0, index + 1);
                s2 = new StringBuffer(s1).reverse().toString();
                if (s1.equals(s2)) {
                    System.out.println("加入字符串:" + s1);
                    list.add(s1);
                }
                index = str.substring(0, index).lastIndexOf(c);
            }
        }
        list.sort((x, y) -> y.length() - x.length());
        return list.get(0);
    }
}
